#include "time.hpp"
#include <ctime>

Variable bi_time(vector<Variable>& argv, Environment& env)
{
	(void)env;
	Variable ret;
	int argc = (int)argv.size();
	if(argc > 2) {
		throw_error(ERROR_ARGUMENTCOUNT);
	}
	time_t rawtime;
	struct tm * timeinfo;
	
	time(&rawtime);
	timeinfo = localtime(&rawtime);
	if(argc==1) {
		ret.str = asctime(timeinfo);
		ret.str=ret.str.substr(0,ret.str.size()-1);
		ret.type=tString;
	} else if(argv[1].type==tString) {
		stringstream data;
		string fmt = argv[1].str;
		for(unsigned i=0;i<fmt.size();i++) {
			if( (fmt[i] == '%') && ( i+1 < fmt.size() ) ) {
				switch(fmt[++i]) {
					case 'h':
						data << timeinfo->tm_hour;
						break;
					case 'H':
						if(timeinfo->tm_hour<10){
							data << 0;
						}
						data << timeinfo->tm_hour;
						break;
					case 'm':
						if(timeinfo->tm_min<10){
							data << 0;
						}
						data << timeinfo->tm_min;
						break;
					case 's':
						if(timeinfo->tm_sec<10){
							data << 0;
						}
						data << timeinfo->tm_sec;
						break;
					case 'D':
						if(timeinfo->tm_mday<10){
							data << 0;
						}
						data << timeinfo->tm_mday;
						break;
					case 'd':
						data << timeinfo->tm_mday;
						break;
					case 'M':
						data << timeinfo->tm_mon + 1;
						break;
					case 'y':
						data << timeinfo->tm_year % 100;
						break;
					case 'Y':
						data << timeinfo->tm_year + 1900;
						break;
					case '%':
						data << '%';
						break;
					default:
						break;
				}
			} else {
				data << fmt[i];
			}
		}
		ret = data.str();
	}
	return ret;
}

Variable bi_sleep(vector<Variable>& argv, Environment& env)
{
	int argc = (int)argv.size();
	Variable ret;
	if(argc != 2) {
		throw_error(ERROR_ARGUMENTCOUNT);
	}
	ret = argv[1];
	env.verify(ret);
	if(ret.type != tNumeric) {
		throw_error(ERROR_ARGUMENTS);
	}
	double seconds = ret.i;
	clock_t endwait;
	endwait = clock () + clock_t(seconds * CLOCKS_PER_SEC);
	while (clock() < endwait) {}
	return ret;
}

Variable bi_timer(vector<Variable>& argv, Environment& env)
{
	int argc = (int)argv.size();
	Variable ret;
	if(argc != 3) {
		throw_error(ERROR_ARGUMENTCOUNT);
	}
	if(argv[1].type!=tVarname || argv[2].type != tVarname) {
		throw_error(ERROR_ARGUMENTS);
	}
	string name = argv[2].str;
	string cmd = argv[1].str;
	if(cmd=="start") {
		ret = env.getvar(name) = clock();
	} else if(cmd=="get") {
		ret = (clock()-env.getvar(name).i)/CLOCKS_PER_SEC;
	} else if(cmd=="stop" || cmd=="clear") {
		env.getvar(name).clear();
	} else {
		throw_error(ERROR_ARGUMENTS);
	}
	return ret;
}
